/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.order.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.order.dto.Customer;
import com.javaeye.common.web.PageInfo;

public class CustomerDAOHibernate extends HibernateDaoSupport implements CustomerDAO {
	
	@SuppressWarnings("unchecked")
	public long getNewCustomerAtMonth(String month) {
		final String queryString = "select count(c.id) from Customer c where c.createDate like ? and c.inuse=1";
		List result = getHibernateTemplate().find(queryString, month + "%");
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	
	@SuppressWarnings("unchecked")
	public long getCustomerCountByCategoryId(int categoryId) {
		final String queryString = "select count(c.id) from Customer c join c.productCategorys pcs where pcs.id=? and c.inuse=1";
		List result = getHibernateTemplate().find(queryString, categoryId);
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	@SuppressWarnings("unchecked")
	public List<Customer> getAutoCompleteCustomers(final String name, final int size) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				final String hql = "select c.id, c.name, c.area from Customer c where c.name like ? and c.inuse=1";
				Query query = session.createQuery(hql);
				query.setParameter(0, "%" + name.trim() + "%");
				query.setFirstResult(0);
				query.setMaxResults(size);
				return query.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				Customer customer = (Customer)contidions;
				Criteria crit = session.createCriteria(Customer.class);
				crit.add(Restrictions.eq("inuse", 1));
				if (!"".equals(customer.getName().trim())) {
					crit.add(Restrictions.like("name", "%" + customer.getName().trim() + "%"));
				}
				if (!"".equals(customer.getArea().trim())) {
					crit.add(Restrictions.like("area", customer.getArea().trim() + "%"));
				}
				if (!"-1".equals(customer.getConditionCategory().trim())) {
					int categoryId = Integer.parseInt(customer.getConditionCategory());
					crit.createAlias("productCategorys", "pc")
					.add(Restrictions.eq("pc.id", categoryId));
				}
				
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@Override
	public void saveCustomer(Customer customer) {
		customer.setInuse(1);
		getHibernateTemplate().saveOrUpdate(customer);
		//logger.debug("Customer id set to: " + customer.getId());
	}

	@Override
	public Customer getCustomer(int id) {
		return (Customer)getHibernateTemplate().get(Customer.class, id);
	}

	@Override
	public void removeCustomer(int id) {
		//load和get不同的是不立即执行查询
		Customer customer = (Customer)getHibernateTemplate().load(Customer.class, id);
		customer.setInuse(0);
		getHibernateTemplate().saveOrUpdate(customer);
		//getHibernateTemplate().delete(o);
	}

}
